const countryEl_one = document.getElementById('country-one');
const countyrEl_two = document.getElementById('countyr-two');
const swapEl = document.querySelector('.swap-btn');
const rateEl = document.getElementById('rate');

const amountEl_one = document.getElementById('amount-one');
const amountEl_two = document.getElementById('amount-two');


/* 汇率换算 */
function calulator() {
    // 获取两国货币
    const country_one = countryEl_one.value;
    const country_two = countyrEl_two.value;

    // console.log(country_one,country_two);
    // 调用汇率api
    fetch("https://open.exchangerate-api.com/v6/latest")
        .then(res => res.json())
        .then(data => {
            const rate = data.rates[country_two] / data.rates[country_one];
            rateEl.innerText = `1 ${country_one} = ${rate} ${country_two}`;
            //   不允许负数的金额
            amountEl_one.value = amountEl_one.value >= 0 ? amountEl_one.value : 0
            amountEl_two.value = (amountEl_one.value * (rate)).toFixed(2);
        });
}

// 事件监听
countryEl_one.addEventListener('change', calulator);
amountEl_one.addEventListener('input', calulator);

countyrEl_two.addEventListener('change', calulator);
amountEl_two.addEventListener('input', calulator);

swapEl.addEventListener('click', function () {
    [countryEl_one.value, countyrEl_two.value] = [countyrEl_two.value, countryEl_one.value];
    calulator();
})

calulator()